import Vue from 'vue'
import Router from 'vue-router'
import ClewView from '@/views/ClewView'
import SignView from '@/views/SignView'
import DiaryDisplayView from '@/views/DiaryDisplay/DiaryDisplayView'
import DiaryRefillView from '@/views/DiaryRefillView'
import BasicInfoView from '@/views/BasicInfo/BasicInfoView'
import StatisticView from '@/views/Statistic/StatisticView'
import DiaryEditView from '@/views/DiaryEdit/DiaryEditView'
import MainView from '@/read/MainView'
import store from '@/store/index.js'

Vue.use(Router)

const routes = [
  // {
  //   path: '/',
  //   redirect: '/clew/'
  // },
  {
    path: '/',
    name: 'MainView',
    component: MainView,
  },
  {
    path: '/clew',
    component: ClewView,
    children: [
      {
        path: '',
        redirect: '/clew/diary'
      },
      {
        path: 'statistic',
        name: 'StatisticView',
        component: StatisticView,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'diary',
        name: 'DiaryDisplayView',
        component: DiaryDisplayView,
        meta: {
          requireAuth: true
        }
      },
      {
        path: 'diaryedit',
        name: 'DiaryEditView',
        component: DiaryEditView
      },
      {
        path: 'diaryRefill',
        name: 'DiaryRefillView',
        component: DiaryRefillView
      },
      {
        path: 'basicinfo',
        name: 'BasicInfoView',
        component: BasicInfoView
      },
      {
        path: 'sign',
        name: 'SignView',
        component: SignView,
        meta: {
          signOut: true
        }
      }
    ]
  }
]

const router = new Router({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)) {
    if (store.state.rule === 100) {
      next()
    } else {
      next({
        path: '/clew/sign',
        query: { redirect: to.fullPath }
      })
    }
  } else if (to.matched.some(record => record.meta.signOut)) {
    if (store.state.rule === 10) {
      next()
    } else {
      next({
        path: '',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

export default router
